package com.tinysand.advert.index.impl;

import com.tinysand.advert.index.IndexAware;
import com.tinysand.advert.index.support.AdUnitObject;
import com.tinysand.advert.index.support.AdUnitRelObject;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * Created By TINY
 * Create Time 2020/2/27
 **/
@Component
public class AdUnitRelIndex
        implements IndexAware<String, AdUnitRelObject> {

    // <adId-unitId, adUnitRelObject>
    private static Map<String, AdUnitRelObject> objectMap;
    // <adIds, unitIds>
    private static Map<Long, Set<Long>> adUnitMap;
    // <unitId, adIds>
    private static Map<Long, Set<Long>> unitAdMap;

    static {
        objectMap = new ConcurrentHashMap<>();
        adUnitMap = new ConcurrentHashMap<>();
        unitAdMap = new ConcurrentHashMap<>();
    }

    @Override
    public AdUnitRelObject get(String key) {
        return objectMap.get(key);
    }

    @Override
    public void add(String key, AdUnitRelObject value) {
        objectMap.put(key, value);

        Set<Long> unitSet = adUnitMap.get(value.getAdId());
        if (CollectionUtils.isEmpty(unitSet)) {
            unitSet = new ConcurrentSkipListSet<>();
            adUnitMap.put(value.getAdId(), unitSet);
        }
        unitSet.add(value.getUnitId());

        Set<Long> adSet = unitAdMap.get(value.getUnitId());
        if (CollectionUtils.isEmpty(adSet)) {
            adSet = new ConcurrentSkipListSet<>();
            unitAdMap.put(value.getUnitId(), adSet);
        }
        adSet.add(value.getAdId());
    }

    @Override
    public void update(String key, AdUnitRelObject value) {
        // 不支持更新操作
    }

    @Override
    public void delete(String key, AdUnitRelObject value) {
        Set<Long> unitSet = adUnitMap.get(value.getAdId());
        if (CollectionUtils.isNotEmpty(unitSet)) {
            unitSet.remove(value.getUnitId());
        }

        Set<Long> adSet = unitAdMap.get(value.getUnitId());
        if (CollectionUtils.isNotEmpty(adSet)) {
            adSet.remove(value.getAdId());
        }
    }

    public List<Long> selectAds(List<AdUnitObject> unitObjects) {
        if (CollectionUtils.isEmpty(unitObjects)) {
            return Collections.emptyList();
        }

        List<Long> result = new ArrayList<>();
        for (AdUnitObject unitObject : unitObjects) {

            Set<Long> adIds = unitAdMap.get(unitObject.getUnitId());
            if (CollectionUtils.isNotEmpty(adIds)) {
                result.addAll(adIds);
            }
        }
        return result;
    }
}
